#include "CGamePanel.h"

TCODConsole* CGamePanel::Panel;
rect CGamePanel::Area;

void CGamePanel::cleanup()
{
	delete Panel;
}

void CGamePanel::draw(char midshape, pair position, unsigned int sight, CDungeonFloor* dungeonFloor, bool lookMode, CPlayer* player)
{
	Panel->clear();

	pair size = dungeonFloor->getSize();

	if (lookMode)
		dungeonFloor->getFovMap()->computeFov(player->getPosition().x(), player->getPosition().y(), sight);
	else
		dungeonFloor->getFovMap()->computeFov(position.x(), position.y(), sight);

	int i = 0, j = 0;
	for (int x = position.x() - Area.lowerRight().x()/2; x < position.x() + Area.lowerRight().x()/2; ++x)
	{
		for (int y = position.y() - Area.lowerRight().y()/2; y < position.y() + Area.lowerRight().y()/2; ++y)
		{
			if (rect(0, 0, size.x()-1, size.y()-1).containsPoint(pair(x, y)))
			{
				CDungeonTile* tile = dungeonFloor->getTile(pair(x, y));

				if (dungeonFloor->getFovMap()->isInFov(x, y))
				{
					if (tile->getShape() != '#')
						Panel->putCharEx(i, j, tile->getShape(), TCODColor::white, TCODColor::black);
					else
						Panel->putCharEx(i, j, tile->getShape(), TCODColor::amber, TCODColor::black);

					if (!tile->seen())
						tile->setSeen(true);

					for (unsigned int nn = 0; nn < dungeonFloor->getTile(pair(x, y))->items.size(); ++nn)
					{
						if (dungeonFloor->getTile(pair(x, y))->items.size() > 1)
							Panel->putCharEx(i, j, dungeonFloor->getTile(pair(x, y))->items[nn]->getShape(), TCODColor::white, TCODColor::copper);
						else
							Panel->putChar(i, j, dungeonFloor->getTile(pair(x, y))->items[nn]->getShape());
					}

					for (unsigned int n = 0; n < dungeonFloor->getTile(pair(x, y))->entities.size(); ++n)
					{
						if (dungeonFloor->getTile(pair(x, y))->entities.size() > 1)
							Panel->putCharEx(i, j, dungeonFloor->getTile(pair(x, y))->entities[n]->getShape(), TCODColor::white, TCODColor::copper);
						else
							Panel->putChar(i, j, dungeonFloor->getTile(pair(x, y))->entities[n]->getShape());
					}
				}
				else if (tile->seen())
					Panel->putCharEx(i, j, tile->getShape(), TCODColor::darkGrey, TCODColor::black);

				if (lookMode && player->getPosition() == pair(x, y))
					Panel->putChar(i, j, player->getShape());
			}

			j++;
		}
		i++;
		j = 0;
	}

	Panel->putChar(Area.width()/2, Area.height()/2, midshape);

	TCODConsole::blit(Panel, 0, 0, Area.width(), Area.height(), TCODConsole::root, Area.upperLeft().x(), Area.upperLeft().y());
}

void CGamePanel::init(rect area)
{
	Area = area;

	Panel = new TCODConsole(Area.width(), Area.height());
}
